﻿
package com.android.finaltracer;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.finaltracer.engine.EngineService;
import com.android.finaltracer.model.FTDataProvider.RelationColumns;
import com.android.finaltracer.ui.MarkerOverlay;
import com.android.finaltracer.ui.MarkerOverlay.PopCallback;
import com.android.finaltracer.util.FTKey;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MKEvent;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.MKLocationManager;
import com.baidu.mapapi.MKMapViewListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapController;
import com.baidu.mapapi.MapView;

/**
 * FuntionActivity is an activity extending com.google.android.maps.MapActivity
 * for containing the com.google.android.maps.MapView.
 * 
 * @author zhuhy1
 */
public class FTMapActivity extends MapActivity implements PopCallback,
        MKMapViewListener {

    private BMapManager mBMapMan = null;
    private MapController mMapController = null;
    private PositionObserver mObserver = null;

    public static final int EVENT_POSITION_CHANGED = 1;
    public boolean showDlg = false;

    public MapView mMapView = null;
    public View mPopView = null; // 气泡View
    public View mFloatBtn = null; // 浮动按钮
    public ListView mListView = null;
    public TextView mTvAddr = null;

    private MarkerOverlay mMarkerOverlay = null;

    // add hw begin 5.22
    private TextView title_tv;
    private ImageView select_bind_phone_iv;
    public static Messenger mService = null;
    private boolean mBound = false;
    private String currentControlNum;

    private ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = new Messenger(service);
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // TODO Auto-generated method stub
            mService = null;
            mBound = false;
        }
    };

    // add hw end 5.22

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fzmapview);
        initTitle();

        // 初始化地图控件
        initMapControl();

        mObserver = new PositionObserver(mHandler);
        getContentResolver().registerContentObserver(
                RelationColumns.CONTENT_URI, true, mObserver);
    }

    private void initMapControl() {
        Log.d("FTMapActivity", "initMapControl");
        mBMapMan = new BMapManager(this);
        mBMapMan.init(getString(R.string.api_key_baidu),
                new MyGeneralListener());
        mBMapMan.getLocationManager().disableProvider(
                MKLocationManager.MK_GPS_PROVIDER);
        mBMapMan.getLocationManager().disableProvider(
                MKLocationManager.MK_NETWORK_PROVIDER);
        mBMapMan.start();

        super.initMapActivity(mBMapMan);

        mMapView = (MapView) findViewById(R.id.mapView);
        mMapView.setBuiltInZoomControls(false); // 设置启用内置的缩放控件
        // mMapView.setDrawOverlayWhenZooming(true);
        // //设置在缩放动画过程中也显示overlay,默认为不绘制

        mMapController = mMapView.getController(); // 得到mMapView的控制权,可以用它控制和驱动平移和缩放
        mMapController.setZoom(15); // 设置地图zoom级别

        // 添加ItemizedOverlay
        Drawable marker = getResources().getDrawable(R.drawable.person); // 得到需要标在地图上的资源
        marker.setBounds(0, 0, marker.getIntrinsicWidth(),
                marker.getIntrinsicHeight()); // 为maker定义位置和边界
        mMarkerOverlay = new MarkerOverlay(this, marker, this);
        mMapView.getOverlays().add(mMarkerOverlay); // 添加ItemizedOverlay实例到mMapView

        // 创建点击mark时的弹出泡泡视图
        mPopView = super.getLayoutInflater().inflate(R.layout.mappopview, null);
        mTvAddr = (TextView) mPopView.findViewById(R.id.addr);

        mMapView.addView(mPopView, new MapView.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, null,
                MapView.LayoutParams.TOP_LEFT));
        mPopView.setVisibility(View.GONE);
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    protected void onPause() {
        Log.d("FTMapActivity", "onPause");
        if (mBMapMan != null) {
            mBMapMan.stop();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        Log.d("FTMapActivity", "onResume");
        if (mBMapMan != null) {
            mBMapMan.start();
        }
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        Log.d("FTMapActivity", "onDestroy");
        if (mBMapMan != null) {
            mBMapMan.destroy();
        }
        if (currentControlNum != null) {
            stopGps(currentControlNum);
        }
        getContentResolver().unregisterContentObserver(mObserver);
        unBindService();
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    // 常用事件监听，用来处理通常的网络错误，授权验证错误等
    static class MyGeneralListener implements MKGeneralListener {
        @Override
        public void onGetNetworkState(int iError) {
            Log.d("FTMapActivity", "network error");
        }

        @Override
        public void onGetPermissionState(int iError) {
            if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
                // 授权Key错误:
                Log.d("FTMapActivity", "api key error");
            }
        }
    }

    private class PositionObserver extends ContentObserver {
        private Handler mHandler = null;

        public PositionObserver(Handler handler) {
            super(handler);
            mHandler = handler;
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onChange(boolean selfChange) {
            Log.d("FTMapActivity", "onChange : " + selfChange);
            mHandler.sendMessage(mHandler.obtainMessage(EVENT_POSITION_CHANGED));
        }
    }

    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case EVENT_POSITION_CHANGED: {

                    Log.d("FTMapActivity", "position db changed");
                    Uri mUri = Uri.parse(RelationColumns.CONTENT_URI.toString());
                    String[] projection = {
                            RelationColumns.NUMBER,
                            RelationColumns.GPS_LAT, RelationColumns.GPS_LNG
                    };
                    String selection = RelationColumns.GPS_TYPE + "> '1' and "
                            + RelationColumns.GPS_ON + "= '2' and "
                            + RelationColumns.GPS_LAT + "<> '0'";
                    Cursor cursor = getContentResolver().query(mUri, projection,
                            selection, null, null);
                    if (cursor != null) {
                        if (cursor.getCount() > 0) {
                            mMarkerOverlay.restoreFromCursor(cursor);
                        }
                        cursor.close();
                    }

                    GeoPoint point = mMarkerOverlay.getFirstPoint();
                    if (point != null) {
                        mMapController.animateTo(point);
                    }
                }
                    break;
            }
        }
    };

    public void updatePositions(Cursor cursor) {
        if (cursor.moveToFirst()) {
            do {
                String number = cursor.getString(cursor
                        .getColumnIndexOrThrow(RelationColumns.NUMBER));
                int lat = cursor.getInt(cursor
                        .getColumnIndexOrThrow(RelationColumns.GPS_LAT));
                int lng = cursor.getInt(cursor
                        .getColumnIndexOrThrow(RelationColumns.GPS_LNG));
                Log.d("FTMapActivity", String.format(
                        "get [%s] position {%d, %d}", number, lat, lng));

                GeoPoint point = new GeoPoint(lat, lng);

                // 构造OverlayItem的三个参数依次为：item的位置，标题文本，文字片段
                mMarkerOverlay.addItem(point, number, number + " is here!");

            } while (cursor.moveToNext());
        }

        // mMapController.animateTo(point);
    }

    @Override
    public void popChanged(GeoPoint pt, boolean visible, String snippet) {
        if (visible == true) {
            mMapView.updateViewLayout(mPopView, new MapView.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, pt,
                    MapView.LayoutParams.BOTTOM_CENTER));
            mPopView.setVisibility(View.VISIBLE);
            mTvAddr.setText(snippet);
        } else {
            mPopView.setVisibility(View.GONE);
        }
    }

    @Override
    public void onMapMoveFinish() {
        // TODO Auto-generated method stub
        /*
         * mMapView.updateViewLayout(mPopView, new
         * MapView.LayoutParams(LayoutParams.WRAP_CONTENT,
         * LayoutParams.WRAP_CONTENT, 0, 0,
         * MapView.LayoutParams.BOTTOM_CENTER));
         */
    }

    // add hw begin 5.22
    private void initTitle() {
        title_tv = (TextView) findViewById(R.id.title_tv);
        select_bind_phone_iv = (ImageView) findViewById(R.id.select_bind_phone_iv);
        select_bind_phone_iv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                showSelectDialog();
            }

        });
    }

    private void showSelectDialog() {
        final ArrayList<String> phones = getAllBindNumbers();
        if (phones == null || phones.size() == 0) {
            Toast.makeText(FTMapActivity.this, "您没有绑定任何手机", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        LayoutInflater factory = LayoutInflater.from(FTMapActivity.this);
        View extEntryView = factory.inflate(R.layout.select_bind_phone_dialog,
                null);
        final AlertDialog dialog = new AlertDialog.Builder(FTMapActivity.this)
                .create();
        dialog.setView(extEntryView, 0, 0, 0, 0);
        dialog.setIcon(Color.parseColor("#FFFFFF"));

        ListView listView = (ListView) extEntryView.findViewById(R.id.listView);
        listView.setAdapter(new ArrayAdapter<String>(FTMapActivity.this,
                R.layout.select_bind_phone_dialog_item, phones));
        dialog.show();
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                String select = phones.get(position);
                if (!select.equals(currentControlNum)) {
                    stopGps(currentControlNum);
                    startGps(select);
                }
                currentControlNum = select;
                dialog.dismiss();
            }

        });
    }

    private ArrayList<String> getAllBindNumbers() {
        ArrayList<String> phoneNums = null;
        Uri phoneUri = Uri
                .parse("content://com.android.ft.provider.data/relations");
        // String selection =
        // RelationColumns.WEIGHT_TYPE+">'"+RelationColumns.WEIGHT_TYPE_COMMEN+"'";
        String selection = RelationColumns.WEIGHT_TYPE + "='"
                + RelationColumns.WEIGHT_TYPE_BINDED + "'";
        Cursor mCursor = getContentResolver().query(phoneUri, null, selection,
                null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            phoneNums = new ArrayList<String>();
            do {
                phoneNums.add(mCursor.getString(mCursor
                        .getColumnIndex(RelationColumns.NUMBER)));
            } while (mCursor.moveToNext());
        }
        return phoneNums;
    }

    private void startGps(String number) {
        if (!mBound || number == null)
            return;

        title_tv.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.scale_in));
        title_tv.setVisibility(View.VISIBLE);
        title_tv.setText(getString(R.string.trace_phone) + number);
        Toast.makeText(FTMapActivity.this, "start gps" + number,
                Toast.LENGTH_SHORT).show();

        // Message msg = Message.obtain(null,
        // EngineService.MSG_UI_SERVICE_STATR_CONTROL, 0, 0);
        // Bundle bundle = new Bundle();
        // //ArrayList<String> relationNumbers =
        // FTProviderInterface.getInstance(this).getAllRelationNumber(RelationColumns.WEIGHT_TYPE+">"+1);
        // bundle.putString(FTKey.KEY_PHONE_NUMBER, number);
        // msg.setData(bundle);

        Message msg = Message.obtain(null,
                EngineService.MSG_UI_SERVICE_STATR_CONTROL, number);

        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void stopGps(String number) {
        title_tv.setVisibility(View.GONE);
        if (!mBound || number == null)
            return;
        Toast.makeText(FTMapActivity.this, "stop gps" + number,
                Toast.LENGTH_SHORT).show();
        Message msg = Message.obtain(null, EngineService.MSG_STOP_GPS, 0, 0);
        Bundle bundle = new Bundle();
        // ArrayList<String> relationNumbers =
        // FTProviderInterface.getInstance(this).getAllRelationNumber(RelationColumns.WEIGHT_TYPE+">"+1);
        bundle.putString(FTKey.KEY_PHONE_NUMBER, number);
        msg.setData(bundle);

        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    private void bindService() {
        if (mBound) {
            return;
        }
        // bind service
        Intent serviceIntent = new Intent(this, EngineService.class);
        mBound = getApplicationContext().bindService(serviceIntent, mConn,
                Context.BIND_AUTO_CREATE);
    }

    private void unBindService() {
        if (!mBound) {
            return;
        }
        getApplicationContext().unbindService(mConn);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        bindService();
    }
}
